package com.weihong.demo.trade;

import com.futu.openapi.*;
import com.futu.openapi.pb.TrdCommon;
import com.futu.openapi.pb.TrdPlaceOrder;
import com.weihong.demo.evn.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class SellService implements FTSPI_Conn, FTSPI_Trd {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final FTAPI_Conn_Trd trd = new FTAPI_Conn_Trd();
    public volatile boolean isConnected = false;
    public volatile boolean isResponse = false;

    public void sell(int trdEnv, long trdAcc,String code,int qty,double price,TrdCommon.TrdSide trdSide) {
        init();
        isResponse = false;

        TrdCommon.TrdHeader header = TrdCommon.TrdHeader.newBuilder()
                .setAccID(trdAcc)
                .setTrdEnv(trdEnv)
                .setTrdMarket(TrdCommon.TrdMarket.TrdMarket_HK_VALUE)
                .build();
        TrdPlaceOrder.C2S c2s = TrdPlaceOrder.C2S.newBuilder()
                .setPacketID(trd.nextPacketID())
                .setHeader(header)
                .setTrdSide(trdSide.getNumber())
                .setOrderType(TrdCommon.OrderType.OrderType_Normal_VALUE)
                .setSecMarket(TrdCommon.TrdSecMarket.TrdSecMarket_HK_VALUE)
                .setCode(code)
//                .setCode("00700")
                .setQty(qty)
//                .setQty(100)
                .setPrice(price)
//                .setPrice(580)
                .build();
        TrdPlaceOrder.Request req = TrdPlaceOrder.Request.newBuilder().setC2S(c2s).build();
        trd.placeOrder(req);
    }

    private void init() {
        if (isConnected) {
            return;
        }

        synchronized (SellService.class) {
            if (isConnected) {
                return;
            }

            trd.setClientInfo("SellService", 3);  //设置客户端信息
            trd.setConnSpi(this);  //设置连接相关回调
            trd.setTrdSpi(this);   //设置交易相关回调
            trd.initConnect(Config.opendIP, (short) Config.opendPort, false);
            while (!isConnected) {
                logger.info("waiting for connect of OrderListService");
                Config.sleepsec(1);
            }
        }
    }

    @Override
    public void onInitConnect(FTAPI_Conn client, long errCode, String desc) {
        if (errCode != 0) {
            logger.error("Trd onInitConnect: ret={} desc={} connID={}", errCode, desc, client.getConnectID());
            System.exit(-1);
        } else {
            isConnected = true;
        }
    }

    @Override
    public void onReply_PlaceOrder(FTAPI_Conn client, int nSerialNo, TrdPlaceOrder.Response rsp) {
        if (rsp.getRetType() != 0) {
            logger.error("TrdPlaceOrder failed: {}", rsp.getRetMsg());
            System.exit(-1);
        }

        logger.info("Receive TrdPlaceOrder: {}", rsp);
    }
}
